package com.lanyu.community.api.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.HashMap;
import java.util.Map;


/**
 * @author suibin。
 * @create 2017-03-23 下午4:25
 **/
public class XmlUtil {

  private static final Logger _log = LoggerFactory.getLogger(XmlUtil.class);

  public static Object XML2Object(Class c, String xml) throws JAXBException, IOException {
    JAXBContext context;
    context = JAXBContext.newInstance(c);
    Unmarshaller unmarshal = context.createUnmarshaller();
    Object obj = unmarshal.unmarshal(new StringReader(xml));
    return obj;
  }

  public static String Object2XML(Object obj) throws JAXBException, IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
      JAXBContext jc = JAXBContext.newInstance(obj.getClass());
      Marshaller m = jc.createMarshaller();
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      m.marshal(obj, os);
      String xml = new String(os.toByteArray(), "UTF-8");
      return xml;
    } finally {
      os.close();
    }
  }

  public static Map<String, Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

    //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream is = getStringStream(xmlString);
    Document document = builder.parse(is);

    //获取到document里面的全部结点
    NodeList allNodes = document.getFirstChild().getChildNodes();
    Node node;
    Map<String, Object> map = new HashMap<String, Object>();
    int i = 0;
    while (i < allNodes.getLength()) {
      node = allNodes.item(i);
      if (node instanceof Element) {
        map.put(node.getNodeName(), node.getTextContent());
      }
      i++;
    }
    return map;

  }

  public static InputStream getStringStream(String sInputString) {
    ByteArrayInputStream tInputStringStream = null;
    if (sInputString != null && !sInputString.trim().equals("")) {
      tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
    }
    return tInputStringStream;
  }

}
